package net.freebytes.websocket.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import java.util.List;

/**
 * 这里的websocket配置是，总共仅开启一个端点（如：/ws），与前端进行实时交互。
 * 前端需要多个实时交互点，那就在/ws后面拼接不同的前缀，如/ws/user1, /ws/user2
 *
 * @author 千里明月
 * @date 2021/8/8
 **/
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${websocket.dest.prefixes}")
    private List<String> destinationPrefixes;

    @Value("${websocket.dest.endPoints:/ws}")
    private String endPoints;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个总端点，前端只通过这个端点进行长连接
        registry.addEndpoint(endPoints)
                //解决跨域问题
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //定义了一个客户端订阅地址的前缀信息，也就是客户端接收服务端发送消息的前缀信息
        registry.enableSimpleBroker(destinationPrefixes.toArray(new String[destinationPrefixes.size()]));
    }

}